package com.rd.server.modules.room.service.impl;

import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.rd.server.modules.room.mapper.RoomUsersMapper;
import com.rd.server.modules.room.model.RoomTransferPO;
import com.rd.server.modules.room.model.RoomUsersPO;
import com.rd.server.modules.room.service.RoomUsersService;
import com.rd.server.modules.user.model.po.UserPO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

import static com.rd.server.modules.room.model.table.RoomTransferTableDef.ROOM_TRANSFER;
import static com.rd.server.modules.room.model.table.RoomUsersTableDef.ROOM_USERS;

/**
 * @ClassName RoomUsersServiceImpl
 * @Description TODO
 * @Author zyy
 * @Date 2025/6/6 22:30
 * @Version 1.0
 **/
@Slf4j
@Service
public class RoomUsersServiceImpl extends ServiceImpl<RoomUsersMapper, RoomUsersPO> implements RoomUsersService {


    @Override
    public List<RoomUsersPO> selectByRoomId(String roomId) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq(ROOM_USERS.ROOM_ID.getName(), roomId);
        queryWrapper.orderBy(ROOM_USERS.CREATED_AT,true);
        return this.list(queryWrapper);
    }

    @Override
    public RoomUsersPO selectByUserIdAndRoomId(String userId, String roomId) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq(ROOM_USERS.USER_ID.getName(), userId);
        queryWrapper.eq(ROOM_USERS.ROOM_ID.getName(), roomId);
        return this.getOne(queryWrapper);
    }


    @Override
    public void joinRoom(String roomId, UserPO userPO) {
        // 先查询是否在房间内
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq(ROOM_USERS.ROOM_ID.getName(), roomId);
        queryWrapper.eq(ROOM_USERS.USER_ID.getName(), userPO.getId());
        List<RoomUsersPO> list = this.list(queryWrapper);
        if (!CollectionUtils.isEmpty(list)) {
            log.error("roomId={}, userId={}, 已在该房间内", roomId, userPO.getId());
            return;
        }
        RoomUsersPO roomUsersPO = new RoomUsersPO();
        roomUsersPO.setRoomId(roomId);
        roomUsersPO.setUserId(userPO.getId());
        roomUsersPO.setAvatar(userPO.getAvatar());
        roomUsersPO.setNickname(userPO.getNickname());
        this.save(roomUsersPO);
    }
}
